<?php
/*********************************************
  CPG Dragonfly™ CMS
  ********************************************
  Copyright © 2004 - 2005 by CPG-Nuke Dev Team
  http://www.dragonflycms.com

  Dragonfly is released under the terms and conditions
  of the GNU GPL version 2 or any later version
**********************************************/
if (!defined('CPG_NUKE')) { exit; }
Dragonfly_Page::setTitle(_SurveysLANG);

if (!isset($_POST['pollid']) && !isset($_GET['pollid']))
{
	$editing = '';
	require_once('header.php');

	$querylang = '';
	if (Dragonfly::getKernel()->L10N->multilingual) { $querylang = "AND (planguage='{$currentlang}' OR planguage='')"; }
	$result = $db->query("SELECT
		poll_id,
		poll_title,
		voters
	FROM {$db->TBL->poll_desc}
	WHERE artid=0 AND poll_ptime<".time()." {$querylang}
	ORDER BY poll_ptime DESC");
	OpenTable();
	echo '<ul>';
	while (list($id, $title, $voters) = $result->fetch_row())
	{
		if (is_admin()) { $editing = ' - <a href="'.URL::admin('Surveys&amp;edit='.$id).'">'._EDIT.'</a>'; }
		echo "<li><a href=\"".URL::index("&amp;pollid={$id}")."\">{$title}</a> ";
		echo "(<a href=\"".URL::index("&amp;pollid={$id}&amp;op=results")."\">"._RESULTS."</a> - {$voters} "._LVOTES."{$editing})</li>\n";
	}
	$result->free();
	echo '</ul>';
	CloseTable();

	$result = $db->query("SELECT
		p.poll_id,
		poll_title,
		voters,
		sid,
		title
	FROM {$db->TBL->poll_desc} p
	INNER JOIN {$db->TBL->stories} s ON (s.poll_id=p.poll_id AND s.ptime<=".time().")
	WHERE artid > 0 {$querylang}
	ORDER BY poll_ptime DESC");
	if ($result->num_rows) {
		OpenTable();
		echo '<div style="text-align:center;">'._SURVEYSATTACHED.'</div>';
		echo '<ul>';
		while (list($id, $title, $voters, $sid, $stitle) = $result->fetch_row()) {
			if (is_admin()) { $editing = ' - <a href="'.URL::admin("Surveys&amp;edit=$id").'">'._EDIT.'</a>'; }
			echo '<li><a href="'.URL::index("&amp;pollid={$id}").'">'.$title.'</a> ';
			echo '(<a href="'.URL::index("&amp;pollid={$id}&amp;op=results").'">'._RESULTS."</a> - {$voters} "._LVOTES."{$editing})<br />\n"
			._ATTACHEDTOARTICLE.' <a href="'.URL::index('News&amp;file=article&amp;sid='.$sid)."\">{$stitle}</a></li>\n";
		}
		echo '</ul>';
		CloseTable();
	}
	$result->free();
	return;
}

$poll_id = $_POST->uint('pollid') ?: $_GET->uint('pollid');
$op = $_POST->txt('op') ?: $_GET->txt('op');

if (isset($_POST['vote_id']))
{
	$past = time()-86400*30; // 86400 is one day
	$db->exec("DELETE FROM {$db->TBL->poll_check} WHERE time < {$past}");
	if (!pollVoted($poll_id)) {
		$ctime = time();
		$db->exec("INSERT INTO {$db->TBL->poll_check} (user_id, ip, time, poll_id) VALUES ({$userinfo['user_id']}, {$userinfo['user_ip']}, {$ctime}, {$poll_id})");
		$db->exec("UPDATE {$db->TBL->poll_data} SET option_count=option_count+1 WHERE poll_id={$poll_id} AND vote_id=".$_POST->uint('vote_id'));
		$db->exec("UPDATE {$db->TBL->poll_desc} SET voters=voters+1 WHERE poll_id={$poll_id}");
	}
	$forwarder = isset($_POST['forwarder']) ? $_POST['forwarder'] : 0;
	if (strlen($forwarder)<5) $forwarder = URL::index("&pollid={$poll_id}&op=results");
	URL::redirect($forwarder);
}

require_once(__DIR__ . '/comments.php');
require_once(__DIR__ . '/poll.php');

if (isset($_POST['postreply']))
{
	// store the reply
	replyPost($poll_id);
}

if (isset($_GET['reply']))
{
	// reply to comment
	require_once('header.php');
	OpenTable();
	reply($poll_id);
	CloseTable();
}

else if (isset($_POST['preview']))
{
	// Preview the reply before storage
	require_once('header.php');
	OpenTable();
	replyPreview($poll_id);
	CloseTable();
}

else if (isset($_GET['comment']))
{
	require_once('header.php');
	OpenTable();
	// Show comment X
	if (!isset($_GET['pid'])) {
		singlecomment(intval($_GET['comment']), $poll_id);
	} else {
		DisplayComments($poll_id, '', intval($_GET['pid']), intval($_GET['comment']));
	}
	CloseTable();
}

else if ($op == 'results' && $poll_id > 0)
{
	$poll = new Surveys_Poll($poll_id);
	if ($poll->ptime > time()) {
		cpg_error(sprintf(_ERROR_NONE_TO_DISPLAY, strtolower(_SurveysLANG)));
	}

	Dragonfly_Page::setTitle('.: '.$poll->title);
	require_once('header.php');

	$OUT = Dragonfly::getKernel()->OUT;
	$OUT->poll = $poll;
	$OUT->display('Surveys/results');
/*
	OpenTable();
	echo '<b>'._LAST5POLLS." {$MAIN_CFG['global']['sitename']}</b><br /><br />";
	$resu = $db->query("SELECT poll_id, poll_title, voters FROM ".$prefix."_poll_desc WHERE artid=0 AND poll_id<>$poll_id ORDER BY time_stamp DESC LIMIT 5");
	while (list($id, $ptitle, $votes) = $resu->fetch_row()) {
		echo "<b>&#8226;</b>&nbsp;$ptitle ($votes "._LVOTES.")<br /><br />";
	}
	$resu->free();
	echo '<a href="'.URL::index().'"><b>'._MOREPOLLS.'</b></a>';
	CloseTable();
*/
	if ($poll->comments && $userinfo['umode'] != 'nocomments') {
		DisplayComments($poll->id, $poll->title);
	}
}

else
{
	$poll = new Surveys_Poll($poll_id);
	if ($poll->ptime > time()) {
		cpg_error(sprintf(_ERROR_NONE_TO_DISPLAY, strtolower(_SurveysLANG)));
	}

	Dragonfly_Page::setTitle('.: '.$poll->title);
	require_once('header.php');

	$OUT = Dragonfly::getKernel()->OUT;
	$OUT->poll = $poll;

	if ($poll->voted) {
		$OUT->display('Surveys/results');
	} else {
		$OUT->display('Surveys/poll');
	}
}

/*********************************************************/
/* Functions											 */
/*********************************************************/

function pollVoted($poll_id)
{
	global $db, $userinfo;
	$poll_id = intval($poll_id);
	// if you are anonymous and no anonymous votes allowed, you can't vote
	if (is_user()) {
		return $db->count('poll_check', "user_id={$userinfo['user_id']} AND poll_id={$poll_id}");
	}
	list($anonymous) = $db->uFetchRow("SELECT anonymous FROM {$db->TBL->poll_desc} WHERE poll_id={$poll_id}");
	if ($anonymous) {
		// only one anonymous per ip
		return $db->count('poll_check', "user_id=0 AND ip={$userinfo['user_ip']} AND poll_id={$poll_id}");
	}
	return true;
}
